package com.xzcedu.reflection;

import java.lang.reflect.Constructor;

/**
 * @author 徐州城
 * @version 1.0
 * 演示通过反射机制创建实例
 */
public class ReflectionCreateInstance {
    public static void main(String[] args) throws Exception {

        //1. 先取到User的Class 对象
        Class<?> userCls = Class.forName("com.xzcedu.reflection.User");

        //2. 通过public的无参构造器创建实例
        Object o = userCls.newInstance();
        System.out.println(o);

        //3. 通过public的有参构造器创建实例
        /*
            constructor 对象就是
            public User(String name){
                this.name = name;
            }
         */
        //3.1 先得到构造器
        Constructor<?> constructor = userCls.getConstructor(String.class);
        //3.2 创建实例，并传入实参
        Object hate = constructor.newInstance("hate");
        System.out.println("hate=" + hate);

        //4. 通过非public的有参构造器创建实例
        //4.1 先得到private的构造器对象
        Constructor<?> constructor1 = userCls.getDeclaredConstructor(int.class, String.class);
        //4.2 创建实例
        //暴破【暴力破解】，使用反射可以访问private构造器、方法、属性。反射面前，都是纸老虎
        constructor1.setAccessible(true);
        Object user2 = constructor1.newInstance(20, "张三丰");
        System.out.println(user2);
    }
}

class User {
    private int age = 100;
    private String name = "Mistake";

    private User(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public User() {
    }

    public User(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "name=" + name +
                ", age=" + age +
                '}';
    }
}